#!/usr/bin/env python3
"""初始化字段配置脚本（多代码片段支持）"""
import sys
import os

# 添加项目路径
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))

from app.database import SessionLocal
from app.models.field_config import FieldConfig
from app.models.scan_task import ScanTask


def init_field_configs():
    """初始化字段配置"""
    db = SessionLocal()
    
    try:
        # 获取任务
        harmony_task = db.query(ScanTask).filter(ScanTask.task_type == "harmony_api_scan").first()
        arkts_task = db.query(ScanTask).filter(ScanTask.task_type == "arkts_consistency_scan").first()
        cjd_task = db.query(ScanTask).filter(ScanTask.task_type == "cjd_consistency_scan").first()
        
        if not arkts_task or not cjd_task:
            print("❌ 未找到必要的扫描任务")
            return
        
        # arkTS一致性扫描任务的代码片段字段配置
        arkts_code_fields = [
            FieldConfig(
                task_id=arkts_task.id,
                field_name="cangjie_code_snippet",
                display_name="Cangjie代码片段",
                field_type="code",
                field_category="issue_extension",
                display_order=10,
                show_in_list=False,
                show_in_detail=True,
                help_text="Cangjie代码片段，用于对比展示"
            ),
            FieldConfig(
                task_id=arkts_task.id,
                field_name="arkts_code_snippet",
                display_name="ArkTS代码片段",
                field_type="code",
                field_category="issue_extension",
                display_order=11,
                show_in_list=False,
                show_in_detail=True,
                help_text="ArkTS代码片段，用于对比展示"
            ),
        ]
        
        for field in arkts_code_fields:
            # 检查是否已存在
            existing = db.query(FieldConfig).filter(
                FieldConfig.task_id == field.task_id,
                FieldConfig.field_name == field.field_name
            ).first()
            if not existing:
                db.add(field)
                print(f"  ✅ 创建字段配置: {field.display_name}")
            else:
                print(f"  ⏭️  字段配置已存在: {field.display_name}")
        
        # cjd一致性扫描任务的代码片段字段配置
        cjd_code_fields = [
            FieldConfig(
                task_id=cjd_task.id,
                field_name="old_value_code",
                display_name="旧值代码",
                field_type="code",
                field_category="issue_extension",
                display_order=10,
                show_in_list=False,
                show_in_detail=True,
                help_text="旧值代码片段，用于对比展示"
            ),
            FieldConfig(
                task_id=cjd_task.id,
                field_name="new_value_code",
                display_name="新值代码",
                field_type="code",
                field_category="issue_extension",
                display_order=11,
                show_in_list=False,
                show_in_detail=True,
                help_text="新值代码片段，用于对比展示"
            ),
        ]
        
        for field in cjd_code_fields:
            # 检查是否已存在
            existing = db.query(FieldConfig).filter(
                FieldConfig.task_id == field.task_id,
                FieldConfig.field_name == field.field_name
            ).first()
            if not existing:
                db.add(field)
                print(f"  ✅ 创建字段配置: {field.display_name}")
            else:
                print(f"  ⏭️  字段配置已存在: {field.display_name}")
        
        db.commit()
        print("\n✅ 字段配置初始化完成！")
        
    except Exception as e:
        db.rollback()
        print(f"❌ 初始化字段配置失败: {e}")
        raise
    finally:
        db.close()


if __name__ == "__main__":
    try:
        print("正在初始化字段配置...")
        init_field_configs()
    except Exception as e:
        print(f"\n❌ 字段配置初始化失败: {e}")
        sys.exit(1)

